﻿using Dapper;
using IRealize;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.Configuration;
using Realize;

namespace WebApplication9.Controllers.Recruit_Manage.ZW
{
    public class EMR_AddController : Controller
    {
        private readonly IConfiguration configuration;

        public EMR_AddController(IConfiguration configuration)
        {
            this.configuration = configuration;
        }
        public IActionResult Index(string success = null, string error = null)
        {
            // 将URL参数传递给视图
            ViewBag.SuccessMessage = success;
            ViewBag.ErrorMessage = error;
            return View();
        }

        // 获取级联数据（I级→II级→III级）
        [HttpGet("FirstLevel1")]
        public async Task<IActionResult> FirstLevel1()
        {
            using (var connection = new SqlConnection(configuration["SqlServer"]))
            {
                await connection.OpenAsync();

                // 查询I级机构
                var firstKinds = await connection.QueryAsync<dynamic>(
                    "SELECT first_kind_id AS id, first_kind_name AS name FROM config_file_first_kind");

                // 构建级联数据结构
                var result = new List<dynamic>();

                foreach (var firstKind in firstKinds)
                {
                    // 查询对应的II级机构
                    var secondKinds = await connection.QueryAsync<dynamic>(
                        "SELECT second_kind_id AS id, second_kind_name AS name " +
                        "FROM config_file_second_kind " +
                        "WHERE first_kind_id = @Id",
                        new { Id = firstKind.id });

                    var secondList = new List<dynamic>();

                    foreach (var secondKind in secondKinds)
                    {
                        // 查询对应的III级机构
                        var thirdKinds = await connection.QueryAsync<dynamic>(
                            "SELECT third_kind_id AS id, third_kind_name AS name " +
                            "FROM config_file_third_kind " +
                            "WHERE second_kind_id = @Id",
                            new { Id = secondKind.id });

                        secondList.Add(new
                        {
                            secondKind.id,
                            secondKind.name,
                            children = thirdKinds
                        });
                    }

                    result.Add(new
                    {
                        firstKind.id,
                        firstKind.name,
                        children = secondList
                    });
                }

                return Ok(result);
            }
        }

        [HttpGet]
        public async Task<IActionResult> select()//职位分类下拉框绑定的数据
        {
            Config_Major_Kind cmk = new Config_Major_Kind();
            List<Entity.Config_Major_Kind> zhi = await cmk.selectCMK(configuration["SqlServer"]);
            return Ok(new
            {
                list = zhi,
            });

        }

        [HttpGet]
        public async Task<IActionResult> selectZwName()//职位分类下拉框绑定的数据
        {
            IConfig_Major_Zw config_Major = new Config_Major_Zw();
            List<Entity.Config_Major_Zw> zhi = await config_Major.select(configuration["SqlServer"]);
            return Ok(new
            {
                list = zhi
            });
        }

        [HttpGet]
        public async Task<IActionResult> selectById(string id)
        {
            IConfig_Major icm = new Config_Major();
            List<Entity.Config_Major> zhi = await icm.selectById(id, configuration["SqlServer"]);
            return Ok(new
            {
                list = zhi,
            });

        }

        [HttpPost]
        public async Task<IActionResult> Add(int first_kind_id, string first_kind_name, int second_kind_id, string second_kind_name,
                                             int third_kind_id, string third_kind_name, int major_kind_id, DateTime Deadline,
                                             string MajorKindName, string EngageType,int major_id,string major_name, int human_amount, string Register, string RegistTime,
                                             string MajorDescribe, string EngageRequired)
        {

            if (first_kind_id == 0 || first_kind_name == "" || second_kind_id == 0 || second_kind_name == "" || third_kind_id == 0 || third_kind_name == "" || major_kind_id <= -1 || MajorKindName == "" || EngageType == "" || human_amount == 0 || Register == "null")
            {
                // 重定向到Index并传递错误消息
                return RedirectToAction("Index", new { error = "输入有空" });
            }


            using (SqlConnection con = new SqlConnection(configuration["SqlServer"]))
            {
                string sql = $@"insert into engage_major_release(first_kind_id,first_kind_name,second_kind_id,second_kind_name,third_kind_id,
                                third_kind_name,major_kind_id,major_kind_name,human_amount,engage_type,deadline,
                                register,major_describe,engage_required,major_id,major_name)
                                values({first_kind_id},'{first_kind_name}',{second_kind_id},'{second_kind_name}',{third_kind_id},
                                '{third_kind_name}','{major_id}','{MajorKindName}',{human_amount},'{EngageType}','{Deadline}','{Register}',
                                '{MajorDescribe}','{EngageRequired}','{major_kind_id}','{major_name}')";

                int result = await con.ExecuteAsync(sql);
                if (result > 0)
                {
                    // 重定向到Index并传递成功消息
                    return RedirectToAction("Index", new { success = "添加成功" });
                }
                else
                {
                    // 重定向到Index并传递失败消息
                    return RedirectToAction("Index", new { error = "添加失败" });
                }
            }
        }
    }
}
